<template>
  <view>
    <!-- 导航栏信息 -->
    <uni-nav-bar fixed statusBar height="90rpx">
      <view
        class="navbar"
        v-if="currentUser?.length !== 0"
        :class="{ active: workMainData?.key }"
        >{{ workMainData?.name }}</view
      >
      <template v-slot:left>
        <uni-icons @click="onBack" type="left" class="nav-icons"></uni-icons
      ></template>
      <template v-slot:right v-if="worktoolStore.deviceId.currDeviceId !== '' && !no_bluedev">
        <template v-if="workMainData.temp !== '3'">
          <uni-icons @click="send" type="arrow-up" class="nav-icons"></uni-icons>
        </template>
        <template v-else>
          <uni-icons @click="send" type="download" class="nav-icons"></uni-icons>
        </template>
      </template>
    </uni-nav-bar>
    <!-- 蓝牙信息 -->
    <!-- {{ currentUser }} -->
    <uni-list>
      <uni-list-item title="实际使用的工具:">
        <template #footer v-if="!no_bluedev">
          <view
            class="tool-button"
            @click="onMatchBluetooth()"
            hover-class="haptics-feedback"
            hover-stay-time="50"
            >搜索</view
          >
          <view
            v-if="worktoolStore.deviceId.currDeviceId !== ''"
            class="tool-button"
            @click="disConn"
            hover-class="haptics-feedback"
            hover-stay-time="50"
            >断开</view
          >
          <view
            v-if="haveDevice"
            class="tool-button"
            @click="clearDevices"
            hover-class="haptics-feedback"
            hover-stay-time="50"
            >清空</view
          >
        </template>
      </uni-list-item>
      <!-- :disabled="index !== currIndex" -->
      <!-- :disabled="deviceId.currDeviceId === ''" -->
      <uni-list-item title="自选工具:">
        <template #footer
          ><switch
            :checked="no_bluedev"
            @change="noBluedev"
            :disabled="!selfChusers?.includes(currentUser[0])"
          />
        </template>
      </uni-list-item>
      <scroll-view class="device-list" scroll-y>
        <template v-if="no_bluedev">
          <uni-list-item :title="worktoolStore.deviceId.currDeviceId"> </uni-list-item>
        </template>
        <template v-else>
          <uni-list-item
            v-for="(item, index) in devicesData"
            :disabled="index !== currIndex || worktoolStore.deviceId.currDeviceId === ''"
            :key="item.id"
            clickable
            @click="onClick(item, index)"
          >
            <template v-slot:body>
              <text :class="{ active: item.key }">{{
                item.deviceId + ' ( ' + item.name + ' )'
              }}</text>
            </template>
          </uni-list-item>
        </template>
      </scroll-view>
    </uni-list>
  </view>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useWorktoolStore, useWorksubStore, useUserStore } from '@/stores'
import { showModal } from '@/utils/utils.js'
import { protosAdapter } from '@/utils/protos/index.js'
import { pause } from 'wot-design-uni/components/common/util.ts'
//引入事先定义的任意组件中的通讯
import { emitter } from '@/EventBus'
import { bluetooth } from '@/utils/bluetooth.js'
import processBLE from '../../utils/processBLE'
import { cmd, toValue } from '@/utils/utils.js'
const worktoolStore = useWorktoolStore()
const worksubStore = useWorksubStore()
const userStore = useUserStore()
const props = defineProps({
  workMainData: Object,
  // workMainId: Number,
  // currentUser: Array,
})
const currentUser = ref([])
const currIndex = ref(-1)
const selfChusers = ref([])
// function onClick(item, index) {
//   currIndex.value = index
//   console.log(currIndex.value)
//   //发出一个事件
//   emitter.emit('onClickBlue', item)
// }
//利用命令获取采集数据
function send() {
  emitter.emit('onSendData')
}
//自选量具标识
const no_bluedev = ref()
// no_bluedev.value = worktoolStore.notBluedev
//搜索后获取的蓝牙设备数据
const devicesData = ref([])
//服务端工具数据
const toolsData = ref({})
//是否当前还有蓝牙设备的标识
const haveDevice = computed(() => {
  return Boolean(devicesData.value.length)
})
//当前使用的设备
// const deviceId = computed(() => {
//   return worktoolStore.deviceId
// })
//当点击自选量具时处理
function noBluedev() {
  no_bluedev.value = !no_bluedev.value
  worktoolStore.notBluedev = no_bluedev.value
  if (no_bluedev.value) {
    uni.showModal({
      title: '输入量具设备编号',
      placeholderText: '输入量具设备编号',
      editable: true,
      confirmText: '确定',
      cancelText: '取消',
      success: function (r) {
        if (r.confirm) {
          if (r.content) {
            // deviceId.value.currDeviceId = r.content
            worktoolStore.deviceId.currDeviceId = r.content
            console.log(worktoolStore.deviceId)
          } else {
            no_bluedev.value = false
            worktoolStore.clearDeviceId()
            // deviceId.value.currDeviceId = ''
          }
        } else if (r.cancel) {
          no_bluedev.value = false
          worktoolStore.clearDeviceId()
          // deviceId.value.currDeviceId = ''
        }
      },
    })
  } else {
    worktoolStore.clearDeviceId()
    // deviceId.value.currDeviceId = ''
  }
  console.log(worktoolStore.deviceId.currDeviceId)
}

onShow(() => {
  // devicesData.value = worktoolStore.devices
  // toolsData.value = worktoolStore.tools
  // no_bluedev.value = worktoolStore.notBluedev
  // currentUser.value = [userStore.userInfo.uid, userStore.userInfo.name]
  // selfChusers.value = userStore.userInfo.selfChusers
  // console.log(selfChusers.value)

  disConn()
})
onMounted(() => {
  devicesData.value = worktoolStore.devices
  toolsData.value = worktoolStore.tools
  // deviceId.value = worktoolStore.deviceId
  no_bluedev.value = worktoolStore.notBluedev
  // console.log('mounted', worktoolStore)
  currentUser.value = [userStore.userInfo.uid, userStore.userInfo.name]
  selfChusers.value = userStore.userInfo.selfChusers
  emitter.on('sendData', sendData)
})
onUnmounted(() => {
  emitter.off('sendData')
  disConn()
})
function onBack() {
  // console.log(props.currentUser)
  if (currentUser.value.length === 0) {
    uni.navigateTo({ url: '/pages/login/login' })
    // uni.reLaunch({ url: '/pages/login/login' })
  } else {
    worksubStore.ClearCurrentWorkMainId()
    // uni.switchTab({ url: '/pages/index/index' }) 改成reLanch，否则不会触发页面的所有生命周期
    uni.reLaunch({ url: '/pages/index/index' })
  }
}
function clearDevices() {
  disConn()
  worktoolStore.clearDevices()
  devicesData.value = worktoolStore.devices
}
//获取所有的蓝牙设备
async function onMatchBluetooth() {
  //测试用
  // let restest = [
  //   {
  //     deviceId: '34:68:B5:67:CB:20',
  //     name: 'GL-BLE#abcd',
  //     RSSI: -49,
  //     localName: 'GL-BLE#abcd',
  //     advertisServiceUUIDs: [
  //       '00001812-0000-1000-8000-00805F9B34FB',
  //       '0000FFB0-0000-1000-8000-00805F9B34FB',
  //     ],
  //   },
  // ]
  //#ifndef H5
  // 引入蓝牙模块
  await bluetooth.openAdapter()
  // 检查蓝牙适配器状态
  await bluetooth.adapterState()
  // 开始扫描附近的蓝牙设备,下面直接设置了固定的serviceId,快速获得deviceId
  const options = { services: ['0000FFB0-0000-1000-8000-00805F9B34FB'], allowDuplicatesKey: false }
  await bluetooth.startDiscovery([])
  // uni.startBluetoothDevicesDiscovery({
  //   //这里过滤特定设备
  //   services: ['0000ffb0-0000-1000-8000-00805f9b34fb'],
  //   allowDuplicatesKey: false,
  //   success: function (res) {
  //     console.log('开始扫描设备', res) //res=[Object] {"errMsg":"startBluetoothDevicesDiscovery:ok"}
  //     // return res 回调里的res返回没用，定义在回调外面的变量会被回调里面的变量覆盖，无法返回。除非重新封装promis
  //   },
  // })
  //获取设备
  uni.showLoading({
    title: '设备扫描中',
  })
  let res = []
  let time = 3
  //扫描蓝牙设备
  let timer = setInterval(async () => {
    time--
    if (time >= 0) {
      let devices = await bluetooth.getDevices()
      console.log('devices', devices)
      res = devices.devices.filter(
        (v) => v.name.startsWith('BEM') || v.name.startsWith('XHXL') || v.name.startsWith('GL-BLE'),
      )
      // let devices = await uni.getBluetoothDevices()
      //注释下面，因为在startBluetoothDevicesDiscovery中，已经设置了用serviceID过滤
      // res = devices.devices.filter((v) => v.name.includes('GL-BLE'))
      // res = devices.devices
    } else {
      // 停止搜索
      await bluetooth.stopDiscovery()
      // uni.stopBluetoothDevicesDiscovery()
      clearInterval(timer)
      uni.hideLoading()
      console.log('res', res)
      res.forEach((v) => {
        //扫描到的设备，工具中没有，需要添加操作
        cleanTools(res)
      })
      if (res.length !== 0) {
        console.log(worktoolStore.devices)
        devicesData.value = worktoolStore.devices
      } //[{"deviceId":"34:68:B5:67:CB:20","name":"GL-BLE#abcd","RSSI":-49,"localName":"...}
      else {
        uni.showModal({
          title: '提示',
          content: '没有找到附近的设备，请确设备是否开机。',
          showCancel: false,
        })
      }
    }
  }, 1000)
  //#endif
}
//这个最后需要返回的设备列表
const res = []
//扫描到的设备，工具中没有，需要添加操作,保证搜索到的设备与工具列表一致，并且更新设备列表
// async function cleanTools(rec, main_id) {
async function cleanTools(rec) {
  //去重
  for (const t of rec) {
    if (res.find((c) => c.deviceId === t.deviceId)) continue
    res.push(t)
  }
  //获取服务器下载的工具列表
  const tools = worktoolStore.tools
  let partno = ''
  let toolkey = false
  // res.forEach(async (v) => {
  for (let v of res) {
    // let v = res[0]
    const tl = tools.find((item) => item.deviceId === v.deviceId)
    //服务器下载的工具没有该deviceid情况
    if (tl == undefined || Object.keys(tl).length === 0) {
      console.log(tl)
      let title = '输入量具的产品号，及是否为关键量具（1为关键，0为非关键量具）'
      let placeholderText = '格式为：0|1@ 产品号'
      let editable = true

      const content = await showModal(title, placeholderText, editable, 1)
      console.log('c', content)
      let p = content.indexOf('@')
      if (p >= 0) {
        toolkey = content.slice(0, 1) === '1' ? true : false
        partno = content.slice(2).trim()
      }
      //添加到工具列表中（changeTool是需要上传新加的工具）
      let pobj = { deviceId: v.deviceId, partno: partno, key: toolkey, changeTool: 'put' }
      tools.push(pobj)
      v.name = partno
      v.key = toolkey
      console.log('res1', res)
      worktoolStore.setDevices(v)
      devicesData.value = worktoolStore.devices
      //上传新增的工具,因为这时没网络，所以需要放到主页工单页
      //服务器下载的工具列表中有该deviceId，但是没有产品号
    } else if (tl && !tl.partno) {
      console.log('tl-2', tl)
      let title = '输入量具的产品号'
      let placeholderText = '输入产品号'
      let editable = true
      const content = await showModal(title, placeholderText, editable, 2)
      partno = content
      if (v.deviceId === tl.deviceId) {
        //修改工具列表中的产品号
        tl.partno = partno.trim()
        //表示是需要上传修改的工具
        tl.changeTool = 'write'
        v.name = tl.partno
        v.key = tl.key
        console.log('res2', res)
        worktoolStore.setDevices(v)
        devicesData.value = worktoolStore.devices
        //上传修改的数据,因为这时没网络，所以需要放到主页工单页
        // writeToolData(tl.id, { partno: tl.partno })
        //更新设备列表特征值
      }
    } else {
      //最后修改该deviceid的，res（设备列表）
      if (v.deviceId === tl.deviceId) {
        v.name = tl.partno
        v.key = tl.key
        //表示不需要上传的工具
        tl.changeTool = 'no'
      }
      console.log('res3', res)
      worktoolStore.setDevices(v)
      devicesData.value = worktoolStore.devices
    }
  }
}
//点击断开设备后执行
async function disConn() {
  //#ifndef H5
  await bluetooth.closeAdapter()
  console.log('disconn', no_bluedev.value)
  if (!no_bluedev.value) {
    worktoolStore.deviceId.currDeviceId = ''
  }

  // uni.closeBluetoothAdapter({
  //   // deviceId: deviceId.value.currDeviceId,
  //   success: (res) => {
  //     console.log('disconn', no_bluedev.value)
  //     if (!no_bluedev.value) {
  //       deviceId.value.currDeviceId = ''
  //     }
  //   },
  // })
  //#endif
}
async function onClick(item, index) {
  currIndex.value = index
  const worktoolStore = useWorktoolStore()
  console.log(item)
  //#ifndef H5
  if (!worktoolStore.deviceId.currDeviceId) {
    //引入蓝牙模块
    await bluetooth.openAdapter()
    //连接蓝牙
    const device = await bluetooth.createConnection(item)
    const devId = device.deviceId
    console.log('devId', devId)
    const localName = device.localName
    // 设置蓝牙最大传输单元,扭力扳手需要
    if (localName.startsWith('XHXL')) {
      await pause(500)
      await processBLE.setBLEMTU(devId, 127)
    }
    let opts = {}
    //对于不同厂家的蓝牙判断后设置opts
    if (localName.startsWith('GL')) {
      opts = {
        localName,
        notify: {
          characteristicId: '0000FFB2-0000-1000-8000-00805F9B34FB',
          // deviceId: '34:68:B5:67:CB:20',
          // deviceId: item.deviceId,
          deviceId: devId,
          serviceId: '0000FFB0-0000-1000-8000-00805F9B34FB',
        },
        write: {
          characteristicId: '0000FFB2-0000-1000-8000-00805F9B34FB',
          // deviceId: '34:68:B5:67:CB:20',
          // deviceId: item.deviceId,
          deviceId: devId,
          serviceId: '0000FFB0-0000-1000-8000-00805F9B34FB',
        },
      }
    } else if (localName.startsWith('XHXL')) {
      opts = {
        localName,
        write: {
          characteristicId: '0000FFF2-0000-1000-8000-00805F9B34FB',
          deviceId: devId,
          serviceId: '0000FFF0-0000-1000-8000-00805F9B34FB',
        },
        notify: {
          characteristicId: '0000FFF1-0000-1000-8000-00805F9B34FB',
          deviceId: devId,
          serviceId: '0000FFF0-0000-1000-8000-00805F9B34FB',
        },
      }
    }
    worktoolStore.setOpts(opts)
    // 设置当前蓝牙设备所采用的对应通讯协议
    protosAdapter()
    //订阅监听
    await pause(1000)
    const res = await bluetooth.notify(opts, true)
    console.log('notifyBLECharacteristicValueChange success', res.errMsg)
    console.log('opts', opts)
    console.log('device', [devId, localName])
    worktoolStore.deviceId.currDeviceId = opts.notify.deviceId
    console.log('currDeviceId', worktoolStore.deviceId.currDeviceId)
    //监听蓝牙设备采集的数据
    //uniapp监听蓝牙设备后就关不了，每次执行都会产生监听，所以在APP执行监听，然后在这里获取，避免重复产生
    uni.$on(uni.$myNotifyEventName, (result) => {
      // console.log('result', result)
      let logItem = getApp().globalData.protosUtils.formatDeviceData(result) //这里的cmdVal是readType=log的心跳数据
      // console.log('logItem', logItem)
      //如果是量具采集的数据做如下处理
      if (logItem.measValue !== undefined) {
        let readVal = logItem.measValue
        let gotValue = []
        // let readVal = cmd.ab2char(result.value)
        if (readVal.join('') !== 'MEAS:OK') {
          let value = toValue(readVal).value
          let unit = toValue(readVal).unit
          gotValue[0] = value
          gotValue[1] = unit
          console.log(gotValue)
          emitter.emit('process', gotValue)
        }
      }
    })
  } else if (item.deviceId !== worktoolStore.deviceId.currDeviceId) {
    console.log('item.deviceId-currentDeviceid', [
      item.deviceId,
      worktoolStore.deviceId.currDeviceId,
    ])
    // bluetooth.closeConnection(deviceId.value.currDeviceId)
    //下面的封装增加了uni.$off(uni.$myNotifyEventName)
    bluetooth.closeAdapter()
    worktoolStore.deviceId.currDeviceId = ''
  }
  // #endif
}
//不在量具上采集数据，而在程序中获取数据
async function sendData(args) {
  // emitter.on('sendData', async (currFocus, currInMode, currChkFocus = -1) => {
  const currFocus = args[0]
  const currInMode = args[1]
  console.log('args2', args[2])
  let currChkFocus
  if (!args[2]) {
    currChkFocus = -1
  } else {
    currChkFocus = args[2]
  }
  // console.log('currFocus', currFocus)
  // console.log('currInMode', currInMode)
  // console.log('currChkFocus', currChkFocus)
  const worktoolStore = useWorktoolStore()
  let c = 'MEAS'
  console.log('c', c)
  let cmdHex = cmd.str2HexArr(c)
  console.log('cmdhex', cmdHex)
  const buffer = cmd.arrayToBuffer(cmdHex)
  const opts = worktoolStore.opts

  //当前光标在需要获取(输入)数据的地方，温度湿度的地方已在聚焦的时候，将currentFocus.value设为-1
  if ((currFocus >= 0 || currChkFocus >= 0) && currInMode == 'none') {
    await bluetooth.writeValue(opts, buffer)
  }
}
</script>

<style lang="scss" scoped>
/* 全局优化 */
page {
  background: linear-gradient(135deg, #f0f4fd 0%, #e3eeff 100%);
  min-height: 100vh;
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
}
.device-list {
  max-height: 200px;
}
/* 导航栏优化 */
.navbar {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: 600;
  font-size: 14px;
  color: #2d3748;
  position: relative;

  //&.active::after {
  //   content: '关键设备';
  //   position: absolute;
  //   top: -5px;
  //   right: -45px;
  //   background: #e53e3e;
  //   color: white;
  //   font-size: 10px;
  //   padding: 2px 6px;
  //   border-radius: 10px;
  // }
}

:deep(.nav-icons) {
  font-size: 24px !important;
  color: #1a73e8 !important;
  font-weight: 700 !important;
}

/* 按钮组优化 */
.tool-button {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  height: 36px;
  padding: 0 14px;
  margin-left: 10px;
  background: linear-gradient(90deg, #1a73e8 0%, #0d47a1 100%);
  color: white !important;
  border-radius: 50px;
  font-size: $text-font-size-s;
  font-weight: 500;
  box-shadow: 0 3px 8px rgba(26, 115, 232, 0.2);
  transition: all 0.3s;

  &:active {
    transform: translateY(2px);
    box-shadow: 0 1px 4px rgba(26, 115, 232, 0.2);
  }
}
.active {
  color: #e64340;
}

/* 列表样式优化 */
.uni-list {
  margin: 20px 15px;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.05);

  &::v-deep {
    .uni-list-item__container {
      padding: 16px 20px;
    }

    .uni-list-item__content-title {
      font-weight: 400;
      color: #2d3748;
      font-size: 12px !important;
    }

    .uni-switch-input {
      transform: scale(0.9);
    }

    .uni-switch-input.uni-switch-input-checked {
      background-color: #1a73e8 !important;
      border-color: #1a73e8 !important;
    }
  }
}

/* 设备列表项样式 */
.uni-list-item {
  transition: background-color 0.3s;

  &:active {
    background-color: #f5f7ff;
  }

  text {
    font-size: 15px;
    color: #4a5568;

    &.active {
      color: #e53e3e;
      font-weight: 600;
    }
  }

  /* 设备状态指示器 */
  &::after {
    content: '';
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background: #48bb78;
    margin-left: 10px;
  }

  &[disabled]::after {
    background: #a0aec0;
  }
}

/* 当前设备标识 */
.current-device {
  position: relative;

  &::before {
    content: '';
    position: absolute;
    left: -10px;
    top: 50%;
    transform: translateY(-50%);
    width: 5px;
    height: 20px;
    background: #1a73e8;
    border-radius: 0 5px 5px 0;
  }
}

/* 自定义开关样式 */
.switch-container {
  display: flex;
  align-items: center;

  .switch-label {
    margin-right: 10px;
    font-size: 15px;
    color: #4a5568;
  }
}

/* 动画效果 取消，避免无法区别disable与否的显示 */
// @keyframes fadeIn {
//   from {
//     opacity: 0;
//     transform: translateY(10px);
//   }
//   to {
//     opacity: 1;
//     transform: translateY(0);
//   }
// }

.uni-list-item {
  animation: fadeIn 0.4s ease forwards;

  @for $i from 1 through 5 {
    &:nth-child(#{$i}) {
      animation-delay: $i * 0.08s;
    }
  }
}

/* 响应式调整 */
@media (max-width: 480px) {
  .uni-list {
    margin: 15px 10px;
  }

  .tool-button {
    padding: 0 12px;
    font-size: 13px;
    margin-left: 8px;
  }
}
</style>
<!-- <style lang="scss" scoped>
.navbar {
  // height: 44px;
  width: 100%;
  // text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  // line-height: 44px;
  font-weight: 700;
  font-size: 14px;
}
:deep(.nav-icons) {
  // height: 44px;
  // line-height: 44px;
  // vertical-align: middle;
  font-size: 21px !important;
  font-weight: 700 !important;
}
.active {
  color: #e64340;
}
.tool-button {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 60px;
  height: 26px;
  font-size: $text-font-size-s;
  border: 1px solid $brand-theme-color;
  color: $brand-theme-color;
  margin-left: 10px;
}
</style> -->
